package log

import (
	"errors"
	"log"
	"os"
	"path/filepath"
	"strings"

	"yingsheng.com/go-api-server/config"
	"yingsheng.com/go-api-server/utils"

	"github.com/astaxie/beego/logs"
	beeUtils "github.com/astaxie/beego/utils"
)

var Logger *Log

type Log struct {
	logType   string
	logDate   string
	logPath   string
	isNormal  bool
	beeLogger *logs.BeeLogger
}

// 创建日志助手
func NewLogger(logType string) *Log {
	Logger = &Log{
		logType:   logType,
		logDate:   "",
		logPath:   config.Configer.ApiConf.LogPath,
		isNormal:  false,
		beeLogger: logs.NewLogger(100),
	}

	//异步输出，提升性能
	//lg.BeeLogger.Async()

	return Logger
}

// 检查日志日期，保证按天创建日志文件
func (l *Log) check() {
	d := strings.Split(utils.GetTimeByString(), " ")
	if l.logDate == "" || l.logDate != d[0] {
		var (
			err      error
			filename string
		)
		l.logDate = d[0]

		// 检查日志目录是否存在
		if len(l.logPath) > 0 {
			if !beeUtils.FileExists(l.logPath) {
				err = os.Mkdir(l.logPath, os.ModeDir)
				if err != nil {
					err = errors.New("创建目录失败：" + err.Error())
				}
			}

			filename = l.logPath + "/" + l.logType + "-" + l.logDate + ".log"
		} else {
			if !beeUtils.FileExists("logs") {
				err = os.Mkdir("logs", os.ModeDir)
				if err != nil {
					err = errors.New("创建目录失败：" + err.Error())
				}
			}

			filename = "logs/" + l.logType + "-" + l.logDate + ".log"
			filename = filepath.Join(config.Configer.AppPath, filename)
		}

		if err == nil {
			filename = strings.Replace(filename, "\\", "/", -1)
			l.beeLogger.SetLogger("file", `{"filename":"`+filename+`"}`)
			l.isNormal = true
		} else {
			l.Error(err)
			l.isNormal = false
		}
	}
}

// 记录普通日志信息
func (l *Log) Info(v ...interface{}) {
	//生产环境中不记录Info级别的日志
	if !config.Configer.IsDev() {
		return
	}

	l.check()

	if l.isNormal {
		l.beeLogger.Info(l.generateFmtStr(len(v)), v...)
	}

	if config.Configer.IsDev() || !l.isNormal {
		log.Printf(l.generateFmtStr(len(v)), v...)
	}
}

// 记录错误日志信息
func (l *Log) Error(v ...interface{}) {
	l.check()

	if l.isNormal {
		l.beeLogger.Error(l.generateFmtStr(len(v)), v...)
	}

	if config.Configer.IsDev() || !l.isNormal {
		log.Printf(l.generateFmtStr(len(v)), v...)
	}
}

// 记录严重日志信息
func (l *Log) Critical(v ...interface{}) {
	l.check()

	if l.isNormal {
		l.beeLogger.Critical(l.generateFmtStr(len(v)), v...)
	}

	if config.Configer.IsDev() || !l.isNormal {
		log.Printf(l.generateFmtStr(len(v)), v...)
	}
}

func (l *Log) generateFmtStr(n int) string {
	return strings.Repeat("%v ", n)
}

// 实现nsq日志接口
func (l *Log) Output(calldepth int, s string) error {
	if calldepth == 3 {
		l.Error("NSQ错误：", s)
	} else {
		l.Info("NSQ信息：", s)
	}

	return nil
}
